﻿using MvcWechat.Cryptography;
using MvcWechat.ServiceReference1;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq; 
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Http;
using MvcWechat.Common;

namespace MvcWechat.Controllers
{
    public class OpenController : ApiController
    {
        //
        // GET: /Open/

        [HttpGet]
        //创建key
        public bool DecryptKey2(string key, ref string supplier, ref string customerid)
        {
            bool isKey = false;
            try
            {
                if (key.Contains("_"))
                {
                    var padNum = 0; //去掉的=位数 ,
                    var num = key.Substring(key.LastIndexOf("_")).Replace("_", "");
                    int.TryParse(num, out padNum);
                    key = key.Substring(0, key.LastIndexOf("_")); //去掉占位两位（_x） 后再计算

                    key = Encoding.UTF8.GetString(Convert.FromBase64String(key.PadRight(key.Length + padNum, '=')));
                    var decryptObj = WXBizMsgCrypt.Decrypt(key);
                    var decryptCustomer = decryptObj.Split('_');
                    if (decryptCustomer.Length == 4)
                    {
                        var expirationTime = decryptCustomer[3];
                        DateTime d;
                        DateTime.TryParse(expirationTime, out d);

                        if (d.CompareTo(DateTime.Now) >= 0)
                        {

                            if (decryptCustomer[2] != "")
                            {
                                isKey = true;
                                supplier = decryptCustomer[2];
                            }
                            else
                            {
                                //key用了管理员分配的key
                            }

                            if (decryptCustomer[0] == "")
                            {
                                //key用了管理员分配的key
                            }
                            else
                            {
                                customerid = decryptCustomer[0];

                            }
                            if (customerid != "" && supplier != "")
                            {
                                isKey = true;
                            }

                        }
                        else
                        {  //过期

                        }
                    }
                    else
                    {
                        //解密不对

                    }
                }
                else
                {
                    //格式不对
                }
            }
            catch (Exception ee)
            {

                throw;
            }

            return isKey;
        }
        [HttpPost]
        public JObject QueryStock(string token)
        {
            try
            {
                string customerId = "0";
                string supplier = string.Empty;
                string limit = ConfigurationManager.AppSettings["limit"]; //显示多少应该在一级配置
                if (string.IsNullOrEmpty(limit))
                    limit = "100";
                if (DecryptKey2(token, ref supplier, ref customerId) && Convert.ToInt32(customerId) > 0 && !string.IsNullOrEmpty(supplier))
                {
                    var json = new RetailClient().GetInventoryInfos(GetRequestParam(new string[] { "CustomerID", "limit" }, new string[] { customerId, limit }), "open_Interface"); //标识开放接口
                    //HttpRuntime.Cache.Insert(supplier + ":Stock", json, null, DateTime.Now.AddHours(4), TimeSpan.Zero);
                    return JObject.Parse(json);
                }
                else
                {
                    MessageInfo msg = new MessageInfo();
                    msg.msgcode = false; //默认false;
                    msg.msginfo = "验证失败，token错误";
                    return JObject.Parse(JsonConvert.SerializeObject(msg));
                };
            }
            catch (Exception ee)
            {
                //写日志

                MessageInfo msg = new MessageInfo();
                msg.msgcode = false; //默认false;
                msg.msginfo = "验证失败，token错误！";
                return JObject.Parse(JsonConvert.SerializeObject(msg));
            }

        }
        [HttpPost]
        public JObject QueryProductData(string token,string pageIndex,string pageSize)
        {
            try
            {
                string customerId = "0";
                string supplier = string.Empty; 
                if (DecryptKey2(token, ref supplier, ref customerId) && Convert.ToInt32(customerId) > 0 && !string.IsNullOrEmpty(supplier))
                {
                    var json = new RetailClient().GetProductData(GetRequestParam(new string[] { "CustomerID",  "pageIndex", "pageSize" }, new string[] { customerId, pageIndex, pageSize }), "open_Interface"); //标识开放接口
                    //HttpRuntime.Cache.Insert(supplier + ":Stock", json, null, DateTime.Now.AddHours(4), TimeSpan.Zero);
                    return JObject.Parse(json);
                }
                else
                {
                    MessageInfo msg = new MessageInfo();
                    msg.msgcode = false; //默认false;
                    msg.msginfo = "验证失败，token错误";
                    return JObject.Parse(JsonConvert.SerializeObject(msg));
                };
            }
            catch (Exception ee)
            {
                //写日志

                MessageInfo msg = new MessageInfo();
                msg.msgcode = false; //默认false;
                msg.msginfo = "验证失败，token错误！";
                return JObject.Parse(JsonConvert.SerializeObject(msg));
            }

        }

        static CommonPage CP = new CommonPage();
        //序列化加上用户信息
        public string GetRequestParam(string[] _keys = null, string[] _values = null)
        {

            var inputJson = ManagerJson.ToJson(HttpContext.Current.Request.InputStream).Trim();

            if (inputJson == "") inputJson = "{}";
            if (inputJson.StartsWith("{") && inputJson.EndsWith("}"))
            {
                Dictionary<object, object> str = JsonConvert.DeserializeObject<Dictionary<object, object>>(inputJson);
                //销带过来的ActiveIP  HttpUrl
                str.Add("ActiveIP", HttpContext.Current.Request.UserHostAddress);
                //str.Add("OperationUserId", "客户" + HttpContext.Session["UserID"]);
                str.Add("HttpUrl", System.Web.HttpContext.Current.Request.Url.Authority.ToLower());
                if (_keys != null && _values != null)
                {
                    for (int i = 0; i < _keys.Length; i++)
                    {
                        if (str.ContainsKey(_keys[i]))
                            str.Remove(_keys[i]); //防止分销带过来的key
                        str.Add(_keys[i], _values[i]);
                    }
                }

                //新增操作系统，浏览器版本
                //str.Add("Browser", Request.Browser.Browser + Request.Browser.Version);
                str.Add("OpeartionSystem", Environment.OSVersion.VersionString);


                inputJson = JsonConvert.SerializeObject(str);
            }
            if (inputJson.StartsWith("[") && inputJson.EndsWith("]"))
            {
                List<Dictionary<object, object>> listStr = JsonConvert.DeserializeObject<List<Dictionary<object, object>>>(inputJson);
                Dictionary<object, object> str = new Dictionary<object, object>();
                //销带过来的ActiveIP  HttpUrl
                //str.Add("ActiveIP", HttpContext.Current.Request.UserHostAddress);
                //// str.Add("OperationUserId", "团队 " + HttpContext.Session["UserID"]);
                //str.Add("HttpUrl", System.Web.HttpContext.Current.Request.Url.Authority.ToLower());
                if (_keys != null && _values != null)
                {
                    for (int i = 0; i < _keys.Length; i++)
                    {
                        if (str.ContainsKey(_keys[i]))
                            str.Remove(_keys[i]); //防止分销带过来的key
                        str.Add(_keys[i], _values[i]);
                    }
                }
                //新增操作系统，浏览器版本
                //str.Add("Browser", Request.Browser.Browser + Request.Browser.Version);
                //str.Add("OpeartionSystem", Environment.OSVersion.VersionString);

                listStr.Add(str);
                inputJson = JsonConvert.SerializeObject(listStr);
            }
            return inputJson;
        }
        [HttpPost]
        public string SubmitOrdersFromSub(string token)
        {
            try
            {
                string customerId = "0";
                string supplier = string.Empty;
                if (DecryptKey2(token, ref supplier, ref customerId) && Convert.ToInt32(customerId) > 0 && !string.IsNullOrEmpty(supplier))
                {
                    var json = new RetailClient().SubmitOrders(GetRequestParam(new string[] { "CustomerID", "TagKey" }, new string[] { customerId, supplier }), "open_Interface"); //标识开放接口
                    //HttpRuntime.Cache.Insert(supplier + ":Stock", json, null, DateTime.Now.AddHours(4), TimeSpan.Zero);
                    return json;
                }
                else
                {
                    MessageInfo msg = new MessageInfo();
                    msg.msgcode = false; //默认false;
                    msg.msginfo = "验证失败，token错误";
                    return JsonConvert.SerializeObject(msg);
                };
            }
            catch (Exception ex)
            {
                MessageInfo msg = new MessageInfo();
                msg.msgcode = false; //默认false;
                msg.msginfo = "验证失败，token错误！";
                return JsonConvert.SerializeObject(msg);
            }
        }

    }
    public class MessageInfo
    {
        public bool msgcode { get; set; }
        public string msginfo { get; set; }
        public object data { get; set; }
    }
}
